/** 获取文本宽度 */
const getTextWidth = (text: string, font = `normal 14px sans-serif`) => {
  const canvas = document.createElement(`canvas`)
  const context: any = canvas.getContext(`2d`)
  context.font = font
  const metrics = context.measureText(text)
  return metrics.width
}

/** 获取滚动条宽度 */
const getScrollbarWidth = () => {
  const outer: any = document.createElement(`div`)
  outer.style.visibility = `hidden`
  outer.style.width = `100px`
  outer.style.position = `absolute`
  outer.style.top = `-9999px`
  document.body.appendChild(outer)
  const widthNoScroll = outer.offsetWidth // 获取没有滚动条的元素宽度
  outer.style.overflow = `scroll` // 强制滚动条
  const inner = document.createElement(`div`) // 内部创建元素
  inner.style.width = `100%`
  outer.appendChild(inner)
  const widthWithScroll = inner.offsetWidth // 获取内部元素的可视区域，有滚动条
  outer.parentNode.removeChild(outer) // 移除创建的节点
  return widthNoScroll - widthWithScroll // 获取浏览器滚动条宽度
}

/** 文件下载 */
const downloadFile = (url: string) => {
  const frame = document.createElement(`iframe`)
  frame.src = url
  frame.style.display = `none`
  document.body.appendChild(frame)
}

export { getTextWidth, getScrollbarWidth, downloadFile }
